package com.Dao;

import com.entity.Recruitment;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import java.util.List;

/**
 * Created by Administrator on 2017/3/11.
 * 访问招聘公告的相关操作.
 */
public class RecruitmentDao {
    private Session session;
    private SessionFactory sessionFactory;
    Transaction tran=null;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    private Session getSession(){
        return sessionFactory.openSession();
    }



    //添加一个招聘公告
    public void addRecruitment(Recruitment gonggao){
        session=getSession();
        try {
            tran = session.beginTransaction();
            //存入公告
            session.save(gonggao);
            tran.commit();
        }catch (Exception e){
            //事务回滚
            if(tran!=null) tran.rollback();
            e.printStackTrace();
        }finally {
            session.close();
        }
    }

    //查询指定页数的公告,默认每页every条
    public List searchGonggao(int yeshu,int every){
        session=getSession();
        String hql="from Recruitment r order by r.id asc";
        Query query=session.createQuery(hql);
        query.setFirstResult((yeshu-1)*every);
        query.setMaxResults(every);
        List list=query.list();
        return list;
    }

    //查询现在一共有几条公告
    public long searchTotal(){
        session=getSession();
        String hql="select count(r) from Recruitment r";
        Query query=session.createQuery(hql);
        Long count=(Long)query.uniqueResult();
        return count;
    }


    //删除招聘公告
    public void deleteRecruitment(int id){
        session=getSession();
        try {
            tran = session.beginTransaction();
            //加载要删除的公告
            Recruitment r=(Recruitment)session.get(Recruitment.class,new Integer(id));
            //删除公告
            session.delete(r);
            tran.commit();
        }catch (Exception e){
            //事务回滚
            if(tran!=null) tran.rollback();
            e.printStackTrace();
        }
    }
}
